package com.school.movie.common.model;

import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.io.Serializable;
import java.util.Collection;

/**
 * @author yangzy
 * @date 2020/07/06
 * 系统统一返回封装
 */
@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder
public class BaseResponse<T> implements Serializable {

    private String message;
    @Builder.Default
    private int code = ResultCode.SUCCESS.code;
    private T data;
    private Long recordsTotal;
    private Long recordsFiltered;

    private String token;

    public boolean isSuccess() {
        return code == ResultCode.SUCCESS.code;
    }

    public static <T> BaseResponse<T> builders(ResultCode resultCode, T data) {
        BaseResponseBuilder<T> builder = BaseResponse.builder();
        if(data instanceof Collection){
            builder.recordsTotal = (long) ((Collection<?>) data).size();
        }
        return builder
                .code(resultCode.getCode())
                .message(resultCode.getMsg())
                .data(data)
                .build();
    }
}
